Page({
  data: {
    isAgree: false
  },

  onLoad: function (options) {
    // 页面加载时的逻辑
  },

  // 获取手机号
  getPhoneNumber: function (e) {
    if (!this.data.isAgree) {
      wx.showToast({
        title: '请先同意用户协议和隐私政策',
        icon: 'none'
      });
      return;
    }

    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      wx.showLoading({
        title: '登录中...',
      });

      // 先调用wx.login获取code
      wx.login({
        success: (res) => {
          if (res.code) {
            // 获取到code后，将code和加密数据发送到后端
            const loginData = {
              code: res.code,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv
            };

            // TODO: 调用后端接口，发送loginData进行登录
            // 这里模拟登录成功
            setTimeout(() => {
              // 模拟存储用户信息
              const userInfo = {
                phone: '138****8888', // 这里应该是后端解密后的手机号
                nickname: '用户' + Math.floor(Math.random() * 10000)
              };
              
              wx.setStorageSync('userInfo', userInfo);
              wx.setStorageSync('token', 'mock_token_' + Date.now());

              wx.hideLoading();
              wx.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 2000,
                success: () => {
                  // 登录成功后返回上一页
                  setTimeout(() => {
                    wx.navigateBack();
                  }, 2000);
                }
              });
            }, 1500);
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '登录失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          wx.hideLoading();
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '获取手机号失败',
        icon: 'none'
      });
    }
  },

  // 复选框变化
  checkboxChange: function (e) {
    this.setData({
      isAgree: e.detail.value.length > 0
    });
  },

  // 跳转到用户协议
  goToUserAgreement: function () {
    wx.navigateTo({
      url: '/pages/agreement/user/user'
    });
  },

  // 跳转到隐私政策
  goToPrivacyPolicy: function () {
    wx.navigateTo({
      url: '/pages/agreement/privacy/privacy'
    });
  }
}); 